package myPicture;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import db.*;

public class PictureDao {
	private Connection conn;
	public String sql;
	PreparedStatement ps;

	public PictureDao() {
		conn = DBLib.getConn();
	}

	// 添加图片并保存
	public void addPicture(Picture picture) {
		sql = "insert into pictures (uid,name,url) values (?,?,?)";
		try {
			if (conn.isClosed()) {
				conn = DBLib.getConn();
			}
			ps = conn.prepareStatement(sql);
			ps.setInt(1, picture.getUid());
			ps.setString(2, picture.getName());
			ps.setString(3, picture.getUrl());
			ps.execute();
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 通过id和idType找用户的所有照片的信息
	public ArrayList<Picture> getpicture(int id, String idType) {
		String fieldName = "";
		if (idType.equals("user")) {
			fieldName = "uid";
		} else {
			fieldName = "id";
		}
		sql = "select * from  pictures where " + fieldName + "=?";
		ArrayList<Picture> pics = new ArrayList<Picture>();
		try {
			if (conn.isClosed()) {
				conn = DBLib.getConn();
			}
			ps = conn.prepareStatement(sql);
			ps.setInt(1, id);
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				Picture pic = new Picture();
				pic.setId(rs.getInt(1));
				pic.setUid(rs.getInt(2));
				pic.setName(rs.getString(3));
				pic.setUrl(rs.getString(4));
				pics.add(pic);
			}
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return pics;
	}

	// 得到用户的照片数
	public int getPictureCount(int uid) {
		sql = "select count(*) from pictures where uid=?";
		int i = 0;
		try {
			if (conn.isClosed()) {
				conn = DBLib.getConn();
			}
			ps = conn.prepareStatement(sql);
			ps.setInt(1, uid);
			ResultSet rs = ps.executeQuery();
			rs.next();
			i = rs.getInt(1);
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return i;
	}

	// 删除照片
	public void deletePicture(int id) {
		sql = "delete from pictures where id=?";
		try {
			if (conn.isClosed()) {
				conn = DBLib.getConn();
			}
			ps = conn.prepareStatement(sql);
			ps.setInt(1, id);
			ps.executeUpdate();
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 得到照片的路径
	public String geturl(int id) {
		sql = "select url from pictures where id=?";
		String url = "";
		try {
			if (conn.isClosed()) {
				conn = DBLib.getConn();
			}
			ps = conn.prepareStatement(sql);
			ps.setInt(1, id);
			ResultSet rs = ps.executeQuery();
			rs.next();
			url = rs.getString(1);
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return url;
	}

}
